package org.bling.star.server.connect.handlers;

import org.bling.star.common.command.BaseCommand;
import org.bling.star.common.command.ClientCommand;
import org.bling.star.common.command.systems.SystemCommand;
import org.bling.star.common.response.BaseResponse;
import org.bling.star.server.connect.GlobalConnectManager;
import org.bling.star.server.connect.node.InstanceConnection;
import org.bling.star.server.dispatchers.ClientCommandDispatchers;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.DefaultEventExecutor;
import org.bling.star.server.dispatchers.StrategyFactory;
import org.slf4j.Logger;

@ChannelHandler.Sharable
public class StreamServer extends SimpleChannelInboundHandler<Object> {

    private static final Logger log = org.slf4j.LoggerFactory.getLogger(StreamServer.class);
    private static final ChannelGroup channelGroup=new DefaultChannelGroup(new DefaultEventExecutor());//GlobalEventExecutor.INSTANCE
    private ClientCommandDispatchers clientCommandDispatchers;
    public StreamServer(StrategyFactory strategyFactory) {
        this.clientCommandDispatchers = new ClientCommandDispatchers(strategyFactory);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            Channel channel = ctx.channel();
            log.info(msg.toString());
            if(msg instanceof BaseCommand) {
                InstanceConnection connect = (InstanceConnection) GlobalConnectManager.getInstance().getFrom(channel);
                if (msg instanceof SystemCommand) {
                    SystemCommand msg1 = (SystemCommand) msg;//秘钥
                } else if (msg instanceof ClientCommand) {
                    ClientCommand msg1 = (ClientCommand) msg;
                    connect.setUserInfo(msg1.getUserInfo());
                    log.info("请求:{},channel:{}", msg1.toString(), channel.remoteAddress());
                    BaseResponse dispatcher = clientCommandDispatchers.dispatcher(msg1, connect);
                    log.info("向channel:{}发送消息:{}",ctx.channel().remoteAddress(),dispatcher);
                    ctx.writeAndFlush(dispatcher);
                }
            }
        }catch (Exception e) {
            log.warn(e.getMessage());
        }
    }
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(channel.remoteAddress()+"接入!");
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(channel.remoteAddress()+"接出!");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("[服务器提示]:"+channel.remoteAddress()+"上线了!");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.warn(channel.closeFuture().cause().getMessage());
        System.out.println("[服务器提示]:"+channel.remoteAddress()+"下线了!");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
